<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>智能教学助手</h2>
        <p>用户登录</p>
      </div>
      
      <div v-if="!isChangePassword" class="login-form">
        <div class="form-item role-select">
          <label>登录身份</label>
          <el-select v-model="loginForm.role" placeholder="请选择登录身份" style="width: 100%">
            <el-option label="教师" value="teacher" />
            <el-option label="学生" value="student" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </div>

        <div class="form-item login-type">
          <label>登录方式</label>
          <el-radio-group v-model="loginType">
            <el-radio :label="1">{{ loginForm.role === 'student' ? '学号' : loginForm.role === 'admin' ? '账号' : '工号' }}登录</el-radio>
            <el-radio :label="2">手机号登录</el-radio>
          </el-radio-group>
        </div>
        
        <div class="form-item">
          <label>{{ loginType === 1 ? (loginForm.role === 'student' ? '学号' : loginForm.role === 'admin' ? '账号' : '工号') : '手机号' }}</label>
          <input 
            type="text" 
            v-model="loginForm.loginId" 
            :placeholder="loginType === 1 ? (loginForm.role === 'student' ? '请输入学号' : loginForm.role === 'admin' ? '请输入账号' : '请输入工号') : '请输入手机号'"
          />
        </div>
        
        <div class="form-item">
          <label>密码</label>
          <div class="password-input">
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="loginForm.password" 
              placeholder="请输入密码"
            />
            <span 
              class="toggle-password" 
              @click="showPassword = !showPassword"
            >
              <i :class="showPassword ? 'eye-open' : 'eye-close'"></i>
            </span>
          </div>
        </div>
        
        <div class="form-actions">
          <button 
            class="primary-btn" 
            @click="handleLogin" 
            :disabled="isLoading"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
          
          <div class="action-links">
            <a href="#" @click.prevent="forgotPassword">忘记密码?</a>
            <a href="#" @click.prevent="goToRegister">注册账号</a>
          </div>
        </div>
      </div>
      
      <div v-else class="change-password-form">
        <div class="form-item">
          <label>旧密码</label>
          <input 
            type="password" 
            v-model="passwordForm.oldPassword" 
            placeholder="请输入旧密码"
          />
        </div>
        
        <div class="form-item">
          <label>新密码</label>
          <input 
            type="password" 
            v-model="passwordForm.newPassword" 
            placeholder="请输入新密码"
          />
        </div>
        
        <div class="form-item">
          <label>确认新密码</label>
          <input 
            type="password" 
            v-model="passwordForm.confirmPassword" 
            placeholder="请再次输入新密码"
          />
        </div>
        
        <div class="form-actions">
          <button 
            class="primary-btn" 
            @click="handleChangePassword" 
            :disabled="isLoading"
          >
            {{ isLoading ? '提交中...' : '修改密码' }}
          </button>
          
          <button 
            class="secondary-btn" 
            @click="isChangePassword = false"
          >
            返回登录
          </button>
        </div>
      </div>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter();
    const isLoading = ref(false);
    const errorMessage = ref('');
    const showPassword = ref(false);
    const isChangePassword = ref(false);
    const loginType = ref(1); // 默认工号/学号/账号登录
    
    const loginForm = reactive({
      role: 'teacher',
      loginId: '',
      password: '',
    });
    
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    const handleLogin = async () => {
      if (!loginForm.role) {
        errorMessage.value = '请选择登录身份';
        return;
      }
      
      if (!loginForm.loginId) {
        errorMessage.value = loginType.value === 1 
          ? (loginForm.role === 'student' ? '请输入学号' : loginForm.role === 'admin' ? '请输入账号' : '请输入工号')
          : '请输入手机号';
        return;
      }
      
      if (!loginForm.password) {
        errorMessage.value = '请输入密码';
        return;
      }
      
      try {
        isLoading.value = true;
        errorMessage.value = '';
        
        const response = await axios.post('/api/auth/login', {
          role: loginForm.role,
          loginType: loginType.value,
          loginId: loginForm.loginId,
          password: loginForm.password
        });
        
        if (response.data.success) {
          ElMessage.success('登录成功');
          // 根据角色跳转到不同的页面
          switch (loginForm.role) {
            case 'teacher':
              router.push('/');
              break;
            case 'student':
              router.push('/student/dashboard');
              break;
            case 'admin':
              router.push('/admin/dashboard');
              break;
          }
        } else {
          errorMessage.value = response.data.message || '登录失败，请重试';
        }
      } catch (error) {
        console.error('登录错误:', error);
        if (error.response) {
          errorMessage.value = error.response.data?.message || `登录失败 (${error.response.status})`;
        } else if (error.request) {
          errorMessage.value = '服务器无响应，请检查网络连接';
        } else {
          errorMessage.value = '登录请求发送失败，请稍后重试';
        }
      } finally {
        isLoading.value = false;
      }
    };
    
    const handleChangePassword = async () => {
      // 表单验证
      if (!passwordForm.oldPassword) {
        errorMessage.value = '请输入旧密码';
        return;
      }
      
      if (!passwordForm.newPassword) {
        errorMessage.value = '请输入新密码';
        return;
      }
      
      if (passwordForm.newPassword.length < 6) {
        errorMessage.value = '新密码长度不能少于6位';
        return;
      }
      
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        errorMessage.value = '两次输入的新密码不一致';
        return;
      }
      
      try {
        isLoading.value = true;
        errorMessage.value = '';
        
        const response = await axios.post('/api/auth/change-password', passwordForm, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        });
        
        if (response.data.success) {
          alert('密码修改成功，请重新登录');
          // 清空表单并返回登录页
          passwordForm.oldPassword = '';
          passwordForm.newPassword = '';
          passwordForm.confirmPassword = '';
          isChangePassword.value = false;
          // 清除token和用户信息
          localStorage.removeItem('token');
          localStorage.removeItem('teacherId');
          localStorage.removeItem('teacherName');
        } else {
          errorMessage.value = response.data.message || '密码修改失败，请重试';
        }
      } catch (error) {
        console.error('修改密码错误:', error);
        errorMessage.value = error.response?.data?.message || '操作失败，请稍后重试';
      } finally {
        isLoading.value = false;
      }
    };
    
    const forgotPassword = () => {
      isChangePassword.value = true;
    };
    
    const goToRegister = () => {
      router.push('/register');
    };
    
    return {
      isLoading,
      errorMessage,
      showPassword,
      isChangePassword,
      loginType,
      loginForm,
      passwordForm,
      handleLogin,
      handleChangePassword,
      forgotPassword,
      goToRegister
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 5px;
}

.login-header p {
  color: #666;
  font-size: 16px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-item input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-item input:focus {
  border-color: #1890ff;
  outline: none;
}

.password-input {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #999;
}

.form-actions {
  margin-top: 24px;
}

.primary-btn {
  width: 100%;
  padding: 10px;
  background-color: #1890ff;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.primary-btn:hover {
  background-color: #40a9ff;
}

.primary-btn:disabled {
  background-color: #1890ff;
  opacity: 0.7;
  cursor: not-allowed;
}

.secondary-btn {
  width: 100%;
  padding: 10px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 16px;
  cursor: pointer;
  margin-top: 12px;
  transition: all 0.3s;
}

.secondary-btn:hover {
  background-color: #e6e6e6;
}

.forgot-password {
  text-align: center;
  margin-top: 16px;
}

.action-links {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
}

.action-links a {
  color: #1890ff;
  text-decoration: none;
}

.error-message {
  margin-top: 16px;
  color: #f5222d;
  text-align: center;
}

.eye-open::before {
  content: '👁️';
}

.eye-close::before {
  content: '👁️‍🗨️';
}

.login-type {
  margin-bottom: 15px;
}

.login-type-options {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.login-type-options span {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  cursor: pointer;
  background: #f5f7fa;
  transition: all 0.3s;
}

.login-type-options span.active {
  background: #1a73e8;
  color: white;
}

.login-type-group {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.login-type-group :deep(.el-radio) {
  margin-right: 20px;
  color: #333;
}

.login-type-group :deep(.el-radio__label) {
  font-size: 16px;
}

.login-type-group :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #1a73e8;
}
</style> 